<?php


namespace app\guild\controller;


use app\common\model\GuildTransferModel;
use app\common\model\GuildUserApplyModel;
use app\common\model\NoticeModel;
use app\common\model\UserModel;
use think\Db;
use think\facade\Request;

class ApplyController extends BaseController {

    /**
     * 入会退会申请
     * @return mixed
     */
    public function index() {
        $type_cate = GuildUserApplyModel::TYPE_CATE;
        $this->assign('type_cate', $type_cate);
        return $this->fetch();
    }


    public function get_list() {
        $type      = Request::param("type");
        $status    = Request::param("status");
        $anchor_id = Request::param("anchor_id");
        $page      = Request::param("page");
        $limit     = Request::param("limit");

        $where[] = "guild_id={$this->guild_id}";

        if ($this->hight_auth != 1) {
            $next_uid = parent::getGuildUserId();
            $next_uid = $next_uid ? implode(',', $next_uid) : '0';
            $where[]  = "(uid IN($next_uid) OR guild_manager_id={$this->manager_id})";
        }

        if (is_numeric($type)) {
            $where[] = "type=$type";
        }
        if (is_numeric($status)) {
            $where[] = "status=$status";
        }
        if (is_numeric($anchor_id)) {
            $where[] = "uid=$anchor_id";
        }

        $where = implode(' AND ', $where);

        $userlist = GuildUserApplyModel::with('user')
            ->where($where)->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($userlist) > 0) {
            $count = GuildUserApplyModel::where($where)->count();

            foreach ($userlist as &$item) {
                $item->type_text = $item->type_text;
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 申请入会状态审核
     * @return \think\response\Json
     */
    public function operate_apply_status() {
        $status = Request::param('status');
        $id     = Request::param('id');
        if (!in_array($status, [1, 2])) {
            return self::bulidFail('请正确选择操作');
        }

        $where = [
            ['guild_id', '=', $this->guild_id],
            ['id', '=', $id]
        ];

        $apply = GuildUserApplyModel::where($where)->find();
        if (empty($apply)) {
            return self::bulidFail('没有需要审核的申请');
        }

        if (!in_array($apply->type, [1, 2])) {
            return self::bulidFail('没有需要审核的申请');
        }

        if ($apply->status == $status || $apply->status != 0) {
            return self::bulidFail('该主播申请已审核过，无需再次审核');
        }

        $user = UserModel::where(['id' => $apply->uid])->find();
        if ($status == 1 && $user->status != 0) {
            return self::bulidFail('该用户账号状态异常');
        }

        // 如果是同意设置，则要判断
        // 1、入会需判断有没有所属代理
        // 2、退会是不是属于该代理，或经纪人下属主播
        if ($status == 1) {
            switch ($apply->type) {
                case 1:
                    // 入会
                    if ($user->guild_id > 0) {
                        return self::bulidFail('该用户已经加入其他代理，请拒绝');
                    }
                    break;
                case 2:
                    // 退会
                    if ($user->guild_id != $this->guild_id) {
                        return self::bulidFail('该用户不属于你所在的代理');
                    }

                    // 如果不是超管和管理员操作，则要判断是不是属于经纪人的下属主播
                    $next_uid = parent::getGuildUserId();
                    if ($this->hight_auth != 1 && !in_array($user->id, $next_uid)) {
                        return self::bulidFail('该用户不属于你所在的代理');
                    }

                    break;
            }
        }


        $apply->status       = $status;
        $apply->operate_time = nowFormat();

        if ($apply->type == 1) {
            $notice_content = '入会申请审核被拒绝';
            if ($status == 1) {
                $user->guild_id = $apply->guild_id;
                $user->guild_manager_id = $apply->guild_manager_id;
                $user->guild_join_time = nowFormat();
                $notice_content = '入会申请审核通过';
            }
        } else {
            $notice_content = '退会申请审核被拒绝';
            if ($status == 1) {
                $user->guild_id = 0;
                $user->guild_manager_id = 0;
                $notice_content = '入会申请审核通过';
            }
        }

        Db::startTrans();
        try {
            if (!$user->save()) {
                throw new \Exception('操作失败');
            }

            // 修改审核状态
            if (!$apply->save()) {
                throw new \Exception('操作失败');
            }

            // 添加通知
            $data         = [
                'user_id'     => $apply->uid,
                'title'       => '',
                'content'     => $notice_content,
                'create_time' => nowFormat()
            ];
            $notice_model = new NoticeModel($data);
            if (!$notice_model->save($data)) {
                throw new \Exception('操作失败');
            }

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return self::bulidFail();
    }


    /**
     * 转会申请
     * @return mixed
     */
    public function transfer() {
        return $this->fetch();
    }


    public function get_transfer_list() {
        $status    = Request::param("status");
        $anchor_id = Request::param("anchor_id");
        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $guild_id  = $this->guild_id;

        $where = [
            "(guild_id = {$guild_id} OR into_guild_id = {$guild_id})",
        ];

        // if ($this->hight_auth != 1) {
        //     $next_uid = parent::getGuildUserId();
        //     $next_uid = !empty($next_uid) ? implode(',', $next_uid) : '0';
        //     $where[]  = "uid IN ($next_uid)";
        // }

        if (is_numeric($status)) {
            $where[] = "status={$status}";
        }
        if (is_numeric($anchor_id)) {
            $where[] = "uid={$anchor_id}";
        }
        $where_str = implode(' AND ', $where);

        $guild_transfer_model = new GuildTransferModel();

        $userlist = $guild_transfer_model->with('user')->where($where_str)->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($userlist) > 0) {
            $count = $guild_transfer_model->where($where_str)->count();

            foreach ($userlist as &$item) {
                // 转会类型，1代表转出，2代表转入
                $item->type = ($item->guild_id == $guild_id) ? 1 : 2;
                // 当前代理审核状态 第一视角是转出
                $item->guild_audit_str = $guild_transfer_model->auditStatusText($item->guild_audit);
                // 转入代理审核状态
                $item->into_guild_audit_str = $guild_transfer_model->auditStatusText($item->into_guild_audit);
                // 平台审核状态
                $item->platform_audit_str = $guild_transfer_model->auditStatusText($item->platform_audit);
                // 操作步骤
                $step            = $guild_transfer_model->auditStep($item);
                $item->step      = $step;
                $item->step_text = $guild_transfer_model->auditSptpText($step);
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 转会审核操作
     * @return \think\response\Json
     */
    public function operate_transfer_status() {
        $status = Request::param('status');
        $id     = Request::param('id');
        $type   = Request::param('type');
        if (!in_array($status, [1, 2])) {
            return self::bulidFail('请正确选择操作');
        }

        // 代理id
        $guild_id = $this->guild_id;

        $where = ['id' => $id,];
        if ($type == 1) {
            $where['guild_id'] = $guild_id;
        } else {
            $where['into_guild_id'] = $guild_id;
        }

        // 查询转会信息
        $transfer_info = GuildTransferModel::where($where)->find();
        if (empty($transfer_info)) {
            return self::bulidFail('没有相关转会信息');
        }

        $user = UserModel::where(['id' => $transfer_info->uid])->find();
        if ($user->status != 0) {
            return self::bulidFail('该用户账号状态异常');
        }

        if ($user->guild_id != $transfer_info->guild_id) {
            return self::bulidFail('用户已不属于该代理');
        }

        // 转会类型，1代表转出，2代表转入
        $transfer_info->type = ($transfer_info->guild_id == $guild_id) ? 1 : 2;
        if ($transfer_info->status != 0) {
            return self::bulidFail('当前转会申请已经审核过了');
        }

        if ($transfer_info->type == 1 && $transfer_info->guild_audit != 0) {
            return self::bulidFail('当前转会申请已经审核过了');
        }

        if ($transfer_info->type == 2 && ($transfer_info->guild_audit != 1 || $transfer_info->into_guild_audit != 0)) {
            return self::bulidFail('当前转会申请已经审核了，无需再次审核');
        }

        if ($transfer_info->type == 1) {
            $transfer_info->guild_audit      = $status;
            $transfer_info->guild_audit_time = nowFormat();
            $transfer_info->status           = $status == 2 ? 2 : 0;
        } else {
            $transfer_info->into_guild_audit      = $status;
            $transfer_info->into_guild_audit_time = nowFormat();
            $transfer_info->status                = $status == 2 ? 2 : 0;
        }

        if ($transfer_info->save()) {
            return self::bulidSuccess();
        }

        return self::bulidFail();
    }

}